<!--
  生成对账单对话框组件
  @description 生成对账单功能的对话框组件
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog v-model="dialogVisible" :title="t('settle.reconciliation.generate')" width="600px">
    <div v-loading="loading">
      <!-- 生成表单 -->
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item
          :label="t('settle.reconciliation.reconciliationDate')"
          prop="reconciliationDate"
        >
          <el-date-picker
            v-model="formData.reconciliationDate"
            type="date"
            :placeholder="t('settle.reconciliation.rules.reconciliationDateRequired')"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
          <div class="form-tip">
            {{ t('settle.reconciliation.dateRangeTip') }}
          </div>
        </el-form-item>

        <el-form-item :label="t('settle.reconciliation.merchantNo')" prop="merchantNo">
          <el-select
            v-model="formData.merchantNo"
            :placeholder="t('settle.reconciliation.rules.merchantNoRequired')"
            style="width: 100%"
            filterable
            remote
            :remote-method="searchMerchants"
            :loading="merchantLoading"
            clearable
          >
            <el-option
              v-for="merchant in merchantOptions"
              :key="merchant.merchantNo"
              :label="`${merchant.merchantNo} - ${merchant.merchantName}`"
              :value="merchant.merchantNo"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('settle.reconciliation.channelType')" prop="channelType">
          <el-select
            v-model="formData.channelType"
            :placeholder="t('settle.reconciliation.rules.channelTypeRequired')"
            style="width: 100%"
          >
            <el-option
              v-for="(label, value) in channelTypeOptions"
              :key="value"
              :label="label"
              :value="parseInt(value)"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('settle.reconciliation.autoHandle')" prop="autoHandle">
          <el-switch
            v-model="formData.autoHandle"
            :active-text="t('settle.common.yes')"
            :inactive-text="t('settle.common.no')"
          />
          <div class="form-tip">
            {{ t('settle.reconciliation.autoHandleTip') }}
          </div>
        </el-form-item>

        <el-form-item :label="t('settle.reconciliation.remark')" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :placeholder="t('settle.common.pleaseInput') + t('settle.reconciliation.remark')"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="loading">
        {{ t('settle.common.confirm') }}
      </el-button>
      <el-button @click="dialogVisible = false">
        {{ t('settle.common.cancel') }}
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { processReconciliationFileApi } from '@/api/settle/reconciliation'
import { getMerchantListApi } from '@/api/settle/merchant'
import type { GenerateReconciliationReqVO, MerchantVO } from '@/api/settle/types'
import { ChannelTypeEnum } from '@/api/settle/types'
import { Dialog } from '@/components/Dialog'

defineOptions({ name: 'GenerateReconciliationDialog' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const loading = ref(false)

// 表单相关
const formRef = ref<FormInstance>()
const formData = ref<GenerateReconciliationReqVO>({
  reconciliationDate: '',
  merchantNo: '',
  channelType: ChannelTypeEnum.WECHAT,
  autoHandle: false,
  remark: ''
})

// 商户选项
const merchantOptions = ref<MerchantVO[]>([])
const merchantLoading = ref(false)

// 选项数据
const channelTypeOptions = {
  [ChannelTypeEnum.WECHAT]: t('settle.reconciliation.channelTypes.wechat'),
  [ChannelTypeEnum.ALIPAY]: t('settle.reconciliation.channelTypes.alipay'),
  [ChannelTypeEnum.UNIONPAY]: t('settle.reconciliation.channelTypes.unionpay'),
  [ChannelTypeEnum.DIGITAL_RMB]: t('settle.reconciliation.channelTypes.digitalRmb')
}

// 表单校验规则
const formRules = reactive<FormRules>({
  reconciliationDate: [
    {
      required: true,
      message: t('settle.reconciliation.rules.reconciliationDateRequired'),
      trigger: 'change'
    }
  ],
  merchantNo: [
    {
      required: true,
      message: t('settle.reconciliation.rules.merchantNoRequired'),
      trigger: 'change'
    }
  ],
  channelType: [
    {
      required: true,
      message: t('settle.reconciliation.rules.channelTypeRequired'),
      trigger: 'change'
    }
  ]
})

// 事件定义
const emit = defineEmits(['success'])

/**
 * 打开对话框
 */
const open = () => {
  dialogVisible.value = true
  resetForm()
  loadMerchants()
}

/**
 * 提交生成
 */
const submitForm = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  loading.value = true
  try {
    await processReconciliationFileApi(formData.value)
    ElMessage.success(t('settle.reconciliation.tips.generateSuccess'))
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('生成对账单失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  formData.value = {
    reconciliationDate: '',
    merchantNo: '',
    channelType: ChannelTypeEnum.WECHAT,
    autoHandle: false,
    remark: ''
  }
  formRef.value?.resetFields()
}

/**
 * 加载商户列表
 */
const loadMerchants = async () => {
  try {
    merchantLoading.value = true
    const data = await getMerchantListApi(1) // 只获取审核通过的商户
    merchantOptions.value = data
  } catch (error) {
    console.error('加载商户列表失败:', error)
  } finally {
    merchantLoading.value = false
  }
}

/**
 * 搜索商户
 */
const searchMerchants = async (query: string) => {
  if (query) {
    // 这里可以实现远程搜索逻辑
    await loadMerchants()
  }
}

/**
 * 禁用日期
 */
const disabledDate = (time: Date) => {
  // 禁用未来日期和超过30天的历史日期
  const today = new Date()
  const thirtyDaysAgo = new Date()
  thirtyDaysAgo.setDate(today.getDate() - 30)

  return time.getTime() > today.getTime() || time.getTime() < thirtyDaysAgo.getTime()
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
